// src/services/websocketService.js 文件路径
let socket = null

const connect = (url) => {
  return new Promise((resolve, reject) => {
    if (socket && socket.readyState === WebSocket.OPEN) {
      resolve(socket)
      return
    }

    socket = new WebSocket(url)

    socket.onopen = () => {
      console.log('WebSocket connected to:', url)
      resolve(socket)
    }

    socket.onclose = (event) => {
      console.log('WebSocket disconnected:', event)
      // 可选地，在此处实现重新连接逻辑
    }

    socket.onerror = (error) => {
      console.error('WebSocket error:', error)
      reject(error)
    }

    // 消息处理将由使用该服务的组件进行设置
  })
}

const sendMessage = (message) => {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify(message)) // 假设消息是JSON格式
  } else {
    console.error('WebSocket is not connected.')
  }
}

const onMessage = (callback) => {
  if (socket) {
    socket.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data)
        callback(message)
      } catch (error) {
        console.error('Error parsing WebSocket message:', error)
        // 处理非JSON消息或解析错误
        callback(event.data)
      }
    }
  }
}

const disconnect = () => {
  if (socket) {
    socket.close()
    socket = null
  }
}

export default {
  connect,
  sendMessage,
  onMessage,
  disconnect,
}
